﻿using Dapper;
using System;
using BCEntity.Sim.Company.Position;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.Sim.Company.Position
{
	/// <summary>
	/// 岗位
	/// </summary>
	public class PositionData : IPositionData
	{
		private readonly IDatabaseContext databaseContext;
		private const string QUERY_EXISTS = @"SELECT 1 FROM position";
		private const string QUERY = @"SELECT A.PositionId,A.CreateTime,A.EditAdminId,A.EditAdminName,A.UpdateTime,A.CompanyId,A.DepartmentId,A.ParentPositionId,A.PositionName,A.PositionNo,A.PositionRemark,
											A.Enabled,A.CreateAdminId,A.CreateAdminName,B.CompanyName,C.DepartmentName,D.PositionName AS ParentPositionName
										FROM Position A
										INNER JOIN Company B ON A.CompanyId=B.CompanyId
										INNER JOIN Department C ON A.DepartmentId=C.DepartmentId
										LEFT JOIN Position D ON A.ParentPositionId=D.PositionId";
		public PositionData(IDatabaseContext databaseContext)
		{
			this.databaseContext = databaseContext;
		}
		#region 检查岗位是否存在
		public async Task<bool> Exists(int positionId)
		{
			string sql = string.Format(@"{0} WHERE PositionId=?PositionId LIMIT 1", QUERY_EXISTS);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?PositionId", positionId, DbType.Int32);
			return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
		}
		#endregion

		#region 添加岗位
		public async Task<PositionEntity> Add(PositionEntity entity)
		{
			string sql = SqlCommands.GetInsertSql("position", new string[] { "CompanyId", "DepartmentId", "PositionName", "PositionNo", "CreateAdminId", "CreateAdminName","ParentPositionId", "PositionRemark" });
			sql = string.Format("{0} {1} WHERE A.PositionId=LAST_INSERT_ID();", sql, QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
			parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32, size: 11);
			parameters.Add("?PositionName", entity.PositionName?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?PositionNo", entity.PositionNo?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
			parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
			parameters.Add("?ParentPositionId", entity.ParentPositionId, DbType.Int32, size: 11);
			parameters.Add("?PositionRemark", entity.PositionRemark?.Trim(), DbType.AnsiString, size: 400);
			return await this.databaseContext.Master.QueryFirstOrDefaultAsync<PositionEntity>(sql, parameters, databaseContext.Transaction);
		}
		#endregion

		#region 修改岗位
		public async Task<PositionEntity> Update(PositionEntity entity)
		{
			string sql = SqlCommands.GetUpdateSql("position", new string[] { "EditAdminId", "EditAdminName", "CompanyId", "DepartmentId", "ParentPositionId", "PositionName", "PositionNo", "PositionRemark" }, new string[] { "PositionId" });
			sql = string.Format("{0} {1} WHERE A.PositionId=?PositionId;", sql, QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?PositionId", entity.PositionId, DbType.Int32, size: 11);
			parameters.Add("?EditAdminId", entity.EditAdminId, DbType.Int64, size: 20);
			parameters.Add("?EditAdminName", entity.EditAdminName?.Trim(), DbType.AnsiString, size: 20);
			parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
			parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32, size: 11);
			parameters.Add("?ParentPositionId", entity.ParentPositionId, DbType.Int32, size: 11);
			parameters.Add("?PositionName", entity.PositionName?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?PositionNo", entity.PositionNo?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?PositionRemark", entity.PositionRemark?.Trim(), DbType.AnsiString, size: 400);
			return await this.databaseContext.Master.QueryFirstOrDefaultAsync<PositionEntity>(sql, parameters, databaseContext.Transaction);
		}
		#endregion

		#region 删除岗位
		public async Task<bool> Delete(int positionId)
		{
			string sql = @"DELETE FROM position WHERE PositionId=?PositionId";
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?PositionId", positionId, DbType.Int32);
			return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
		}
		#endregion

		#region 获取岗位
		public async Task<PositionEntity> GetEntity(int positionId)
		{
			string sql = string.Format(@"{0} WHERE A.PositionId=?PositionId LIMIT 1", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?PositionId", positionId, DbType.Int64);
			return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<PositionEntity>(sql, parameters);
		}
		public async Task<PositionEntity> GetEntity(int companyId,int departmentId, string positionNo)
		{
			string sql = string.Format(@"{0} WHERE A.PositionNo=?PositionNo AND A.CompanyId=?CompanyId AND A.DepartmentId=?DepartmentId LIMIT 1", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?CompanyId", companyId, DbType.Int32);
			parameters.Add("?DepartmentId", departmentId, DbType.Int32);
			parameters.Add("?PositionNo", positionNo, DbType.AnsiString);
			return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<PositionEntity>(sql, parameters);
		}
		#endregion

		#region 获取岗位列表
		public async Task<IEnumerable<PositionEntity>> GetList(int companyId, int? departmentId,bool? enabled)
		{
			List<string> wheres = new List<string>();
			DynamicParameters parameters = new DynamicParameters();
			wheres.Add("A.CompanyId=?CompanyId");
			parameters.Add("?CompanyId", companyId, DbType.Int32);
			if (enabled.HasValue)
            {
				wheres.Add("A.Enabled=?Enabled");
				parameters.Add("?Enabled", enabled.Value, DbType.Boolean);
			}
			if (departmentId.HasValue)
			{
				wheres.Add("A.DepartmentId=?DepartmentId");
				parameters.Add("?DepartmentId", departmentId.Value, DbType.Int32);
			}
			string sql = string.Format(@"{0} {1}", QUERY, wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "");
			return await this.databaseContext.Slave.QueryAsync<PositionEntity>(sql, parameters);
		}
		#endregion

		#region 获取岗位分页
		public async Task<(IEnumerable<PositionEntity>, int)> Query(int? companyId, int? departmentId, bool? enabled, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
		{
			List<string> wheres = new List<string>();
			DynamicParameters parameters = new DynamicParameters();
			if (companyId.HasValue)
			{
				wheres.Add("A.CompanyId=?CompanyId");
				parameters.Add("?CompanyId", companyId.Value, DbType.Int32);
			}
			if (departmentId.HasValue)
			{
				wheres.Add("A.DepartmentId=?DepartmentId");
				parameters.Add("?DepartmentId", departmentId.Value, DbType.Int32);
			}
			if (enabled.HasValue)
			{
				wheres.Add("A.Enabled=?Enabled");
				parameters.Add("?Enabled", enabled.Value, DbType.Boolean);
			}
			if (start.HasValue && !end.HasValue)
			{
				wheres.Add("A.CreateTime>=?Start");
				parameters.Add("?Start", start.Value, DbType.DateTime);
			}
			else if (!start.HasValue && end.HasValue)
			{
				wheres.Add("A.CreateTime<=?End");
				parameters.Add("?End", end.Value, DbType.DateTime);
			}
			else if (start.HasValue && end.HasValue)
			{
				wheres.Add("A.CreateTime>=?Start AND A.CreateTime<=?End");
				parameters.Add("?Start", start.Value, DbType.DateTime);
				parameters.Add("?End", end.Value, DbType.DateTime);
			}
			string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; 
										SELECT COUNT(1) FROM position A
										INNER JOIN Company B ON A.CompanyId=B.CompanyId
										INNER JOIN Department C ON A.DepartmentId=C.DepartmentId
										LEFT JOIN Position D ON A.ParentPositionId=D.PositionId {1}",
				  QUERY,
				  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
				  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
				  pageSize,
				  string.IsNullOrWhiteSpace(sortName) ? "A.CreateTime" : "A." + sortName,
				  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
			return await this.databaseContext.Slave.QueryMultipleAsync<PositionEntity, int>(sql, parameters);
		}
		#endregion

		#region 启用岗位
		public async Task<bool> Enabled(int positionId)
		{
			string sql = @"UPDATE position SET Enabled=1 WHERE PositionId=?PositionId";
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?PositionId", positionId, DbType.Int32);
			return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
		}
		#endregion

		#region 禁用岗位
		public async Task<bool> Disabled(int positionId)
		{
			string sql = @"UPDATE position SET Enabled=0 WHERE PositionId=?PositionId";
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?PositionId", positionId, DbType.Int32);
			return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
		}
		#endregion
	}
}



